package id.mankel.commons.crypto.digest;

import id.mankel.commons.crypto.encoding.Encoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Mankel
 */
public class Digests {

    public static String md5(String s) {
        return digest(DigestAlgorithm.MD5, s);
    }

    public static String sha256(String s) {
        return digest(DigestAlgorithm.SHA_256, s);
    }

    public static String sha512(String s) {
        return digest(DigestAlgorithm.SHA_512, s);
    }

    // ==================================================
    // private

    private static String digest(DigestAlgorithm algorithm, String s) {
        return Encoder.toHexString(get(algorithm).digest(s.getBytes(StandardCharsets.UTF_8)));
    }

    private static MessageDigest get(DigestAlgorithm algorithm) {
        try {
            return MessageDigest.getInstance(algorithm.algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

}
